package com.gdzl_hadoop.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class HttpClientUtil {
    private String token;
    //登录的用户信息
    private HashMap<String, String> user;
    //登录的用户权限信息
    private ArrayList<String> pers;
    //错误信息
    private String msg;

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public HashMap<String, String> getUser() {
        return user;
    }

    public void setUser(HashMap<String, String> user) {
        this.user = user;
    }

    public ArrayList<String> getPers() {
        return pers;
    }

    public void setPers(ArrayList<String> pers) {
        this.pers = pers;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public boolean hasLogin(String token, String url) throws Exception {
        if (url == null) throw new Exception("url参数不能为null");
        if (token == null) throw new Exception("token参数不能为null");
        List<NameValuePair> nameValuePairList = new ArrayList<>();
        nameValuePairList.add(new BasicNameValuePair("token", token));
        HashMap responseBody = getRespondy(url, nameValuePairList);
        String code = responseBody.get("code").toString();
        if ("0".equals(code)) {
            return true;
        }
        msg = (String) responseBody.get("msg");
        return false;
    }
    /**
     * @param  url 表示请求的网址
     * @param account 表示进行登录的账户
     * @param password 表示密码
     *  @return 返回代表成功与否的true或false
     */
    public boolean doLogin(String url, String account, String password) throws Exception {
        if (url == null) throw new Exception("url参数不能为null");
        if (account == null) throw new Exception("account参数不能为null");
        if (password == null) throw new Exception("password参数不能为null");
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("email", account));
        params.add(new BasicNameValuePair("password", password));
        HashMap responseBody = getRespondy(url, params);
        //将json信息里的code提出出来，判断请求成功与否,
        String code = responseBody.get("code").toString();
        if ("0".equals(code)) {
            //将responseBody里面的个人信息提取出来
            user = (HashMap) responseBody.get("data");
            //将token提取出来
            token = responseBody.get("token").toString();
            return true;
        } else {
            //将失败信息提取出来
            msg = responseBody.get("msg").toString();
            return false;
        }
    }

    public ArrayList getRoles(String url, String token) throws Exception {
        if (token == null) throw new Exception("token参数不能为null");
        if (url == null) throw new Exception("url参数不能为null");

        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("token", token));
        HashMap responseBody = getRespondy(url, params);
        //将json信息里的code提出出来，判断请求成功与否,
        String code = responseBody.get("code").toString();
        if ("0".equals(code)) {
            //将responseBody里面的角色信息提取出来
            ArrayList roles = (ArrayList) responseBody.get("data");
            int length = roles.size();
            for (Object e : roles) {
                HashMap role = (HashMap) e;
                role.remove("roleId");
                role.remove("adminId");
            }
//            System.out.println(roles);
            return roles;
        } else {
            //将失败信息提取出来
            msg = responseBody.get("msg").toString();
            return null;
        }
    }

    public HashMap getRespondy(String url, List<NameValuePair> params) throws Exception {
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));
            // Create a custom response handler  作用将受到的json字符串信息转换成hashmap
            ResponseHandler<HashMap> responseHandler = new CustomHander();
            //将受到的json字符串信息转换成hashmap
            HashMap responseBody = httpclient.execute(httpPost, responseHandler);
            return responseBody;
        }
    }

}

class CustomHander implements ResponseHandler<HashMap> {

    @Override
    public HashMap<String, Object> handleResponse(HttpResponse httpResponse) throws ClientProtocolException, IOException {
        int status = httpResponse.getStatusLine().getStatusCode();
        if (status >= 200 && status < 300) {
            HttpEntity entity = httpResponse.getEntity();
//                    System.out.println(EntityUtils.toString(entity));
            String s = EntityUtils.toString(entity);
            HashMap<String, Object> resultUtil = JsonUtils.jsonToPojo(s, HashMap.class);
            return resultUtil != null ? resultUtil : null;
        } else {
            throw new ClientProtocolException("Unexpected response status: " + status);
        }
    }
}
